<script setup>
import { ref, reactive, watch, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useIuserInfoStore, useCurrentWatchStore } from '@T2/store/users.ts';
import { statementApi, statementMultiple } from '@T2/service/api.ts';
import UnitByPosition from '@T2/views/Project/Manage/components/tree/unitByPosition.vue';
import Charts from './components/charts.vue';
import AddEditMain from './components/addEditMain.vue';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['376', '377', '378']);

const Resd = reactive({
  unit: {},
  showUnitSelect: false,
  statementList: [],
});
const unitlistChange = (data) => {
  Resd.showUnitSelect = data.length > 1 ? true : false;
}
const positionChange = (data, node) => {
  Resd.unit = data;
  getStatement();
}
const getStatement = () => {
  Resd.statementList = [];
  statementApi({
    method: 'get',
    params: {
      uunit: Resd.unit.id,
      rtype: '分组',
    }
  }).then(res => {
    Resd.statementList = res.results || [];
  });
}


/* 新增编辑弹窗相关 */
const addEditMain = reactive({
  type: '',   //新增、编辑
  content: {},
});
const addMainClick = (isAble = false) => {
  if (!isAble) {
    return;
  }
  if (!Resd.unit) {
    ElMessage.warning('请先在树形图上选择一个站点');
    return;
  }
  addEditMain.type = '新增';
  addEditMain.content = {
    unit: Resd.unit,
    project: curProject.id,
  };
}
const editMainClick = (isAble = false, item) => {
  if (!isAble) {
    ElMessage.error('您没有编辑权限！')
    return;
  }
  addEditMain.type = '编辑';
  addEditMain.content = {
    unit: Resd.unit,
    project: item.project,
    statement: item.id,
    statementName: item.name,
    statementType: item.type,
  };
}
const closeMain = (refresh) => {
  addEditMain.type = '';
  addEditMain.content = {};
  if (refresh) {
    getStatement();
  }
}

/* 删除相关 */
const deleteResd = reactive({
  active: false,
  ids: [],
});
const handleMulDel = (isAble = false) => {
  if (!isAble) {
    return;
  }
  deleteResd.active = true;
}
const checkChange = (statementID, value) => {
  if (value) {
    deleteResd.ids.push(statementID);
  } else {
    deleteResd.ids = deleteResd.ids.filter(id => id !== statementID);
  }
}
const deleteStatementMultipleClick = () => {
  if (!deleteResd.ids.length) {
    ElMessage.error('请选择至少一个选项');
    return;
  }
  let arrs = Resd.statementList.filter(item => deleteResd.ids.includes(item.id));
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #000;'}, '您确认要删除吗？'),
      h('p',{ style:'margin:12px 0;font-size:14px;color: rgba(18,30,52,0.6)' },`${arrs.map(item => item.name).join(' ')} 将被删除`),
      h('p',{ style:'margin:12px 0;font-size:14px;color: #4D92F5' },'注：删除曲线分组后历史数据不会被删除，重建分组时历史数据自动显示'),
    ]),
    type: 'warning',
    confirmButtonText: '删除',
  }).then(() => {
    statementMultiple({
      method: 'delete',
      data: {
        ids: deleteResd.ids,
      }
    }).then(res => {
      ElMessage.success('批量删除成功');
      getStatement();
      deleteResd.active = false;
    }).catch(e => {
      ElMessage.error('批量删除失败');
      deleteResd.active = false;
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
</script>

<template>
  <div class="view flex">
    <div class="position" v-show="Resd.showUnitSelect">
      <UnitByPosition @current-change="positionChange" @unitlist-change="unitlistChange"/>
    </div>
    
    <div class="card-box flex-column">
      <div class="header flex-end-center">
        <template v-if="!deleteResd.active">
          <el-button @click="handleMulDel(RIGHT['378'])" :disabled="!RIGHT['378']">
            批量删除
          </el-button>
        </template>
        <template v-else>
          <el-button @click="deleteStatementMultipleClick()">删 除</el-button>
          <el-button @click="deleteResd.ids = []; deleteResd.active = false">取 消</el-button>
        </template>
        <el-button type="primary" @click="addMainClick(RIGHT['376'])" :disabled="!RIGHT['376']">
          新 增
        </el-button>
      </div>
      <div class="cards flex flex-wrap scroller-aside">
        <div class="cardBox flex-center" v-for="(item, index) in Resd.statementList">
          <Charts
            :deleteActive="deleteResd.active"
            :statement="item"
            @checkChange="checkChange"
            @editStatement="editMainClick(RIGHT['377'], item)"
          />
        </div>
      </div>
    </div>
  </div>
  <AddEditMain
    v-if="addEditMain.type && addEditMain.content.unit?.id"
    :type="addEditMain.type"
    :content="addEditMain.content"
    @close="closeMain"
  />
</template>

<style lang="scss" scoped>
.view {
  width: 100%;
  height: 100%;
}
.position {
  width: fit-content;
  height: calc(100% - 20px);
  background: #FFFFFF;
  box-shadow: 0px 0px 2px 0px rgba(0,0,0,0.15);
  border-radius: 10px;
  margin: 10px;
}
.card-box {
  width: 100%;
  .header {
    padding: 20px;
    .el-button:nth-last-child(n+2) {
      color: #4D92F5;
      border-color: #4D92F5;
    }
  }
  .cards {
    flex: 1;
    overflow-x: hidden;
    overflow-y: overlay;
  }
}
.cardBox {
  width: calc(100% / 3);
  min-width: 400px;
  margin-bottom: 20px;
}
:deep(.el-message-box__container) {
  display: flex;
}
</style>